import Console from '@/components/Console';
import Editor from '@/components/Editor';
import Executions from '@/components/Executions';
import PageWrapper, { Content } from '@/components/PageWrapper';
import { DEFAULT_CODE_TEMPLATE } from '@/constants';
import { exec } from '@/services/api';
import { ReloadOutlined } from '@ant-design/icons';
import { useModel } from '@umijs/max';
import { Badge, Button, Space, Tabs, Tooltip, message } from 'antd';
import { useCallback, useEffect, useMemo, useState } from 'react';
import styles from './index.less';

const HomePage = () => {
  const [tab, setTab] = useState('editor');
  const [consoleOpen, setConsoleOpen] = useState(false);
  const [running, setRunning] = useState(false);
  const [result, setResult] = useState();
  const { codeData, executions, saveCode, saveExecution } = useModel('editor');

  const code = useMemo(() => {
    return codeData || DEFAULT_CODE_TEMPLATE;
  }, [codeData]);
  useEffect(() => {
    if (result?.id) {
      saveExecution(result);
    }
  }, [result]);

  const handleRun = useCallback(() => {
    setRunning(true);
    setConsoleOpen(true);
    exec(code)
      .then((res) => {
        setResult({
          ...res,
          code,
          time: new Date().getTime(),
        });
        setRunning(false);
      })
      .catch((error) => {
        message.error(error.message || 'Execution failed');
        setRunning(false);
      });
  }, [code, exec]);
  const handleCommit = useCallback(() => {}, []);
  const handleResetCode = useCallback(() => {
    saveCode(DEFAULT_CODE_TEMPLATE);
  }, [saveCode]);

  return (
    <div className={styles.container}>
      <PageWrapper>
        <Content>
          <div className="code-zone">
            <div className="card code-editor">
              <div className="e-header">
                <div className="eh-left">
                  <Tabs
                    value={tab}
                    onChange={setTab}
                    items={[
                      {
                        key: 'editor',
                        label: <b>Editor</b>,
                      },
                      {
                        key: 'executions',
                        label: (
                          <Space>
                            <b>Executions</b>
                            <Badge
                              color="blue"
                              count={executions?.length || 0}
                            />
                          </Space>
                        ),
                      },
                    ]}
                  />
                </div>
                <div className="eh-right">
                  {tab === 'editor' && (
                    <Tooltip title="Reset code to defualt template">
                      <Button type="text" onClick={handleResetCode}>
                        <ReloadOutlined />
                      </Button>
                    </Tooltip>
                  )}
                </div>
              </div>
              {tab === 'editor' && (
                <>
                  <div className="e-content">
                    <Editor value={code} onChange={saveCode} />
                  </div>
                  <div className="e-footer">Auto saved</div>
                </>
              )}
              {tab === 'executions' && (
                <>
                  <div className="e-content">
                    <Executions data={executions} />
                  </div>
                </>
              )}
            </div>
            {tab === 'editor' && (
              <div className="card code-result">
                <Console
                  open={consoleOpen}
                  setOpen={setConsoleOpen}
                  onRun={handleRun}
                  onCommit={handleCommit}
                  result={result}
                  running={running}
                />
              </div>
            )}
          </div>
        </Content>
      </PageWrapper>
    </div>
  );
};

export default HomePage;
